//
//  TPBaseTableViewCell.m
//  CloudAtCostPanel
//
//  Created by leonardo on 2017/2/19.
//  Copyright © 2017年 tanpengsccd. All rights reserved.
//

#import "TPBaseTableViewCell.h"




#pragma mark -----TPCellUtilityBtns-------

@implementation TPCellUtilityBtns

- (instancetype)init
{
    @throw [NSException exceptionWithName:@"USE initWithTitles" reason:nil userInfo:nil];
}
- (instancetype)initWithTitles:(NSArray <NSString *> *)titles Colors:(NSArray <UIColor *> *)colors width:(CGFloat)width
{
    self = [super init];
    if (self) {
        
        NSAssert(titles.count == colors.count, @"title's count isn't equal to colors");
        _width_max = width;
        _numberOfBtn = titles.count;
        UIView * lastBtn;
        NSUInteger index = 0;
        for (NSString * title in titles) {
            UIView * btn = [UIView new];
            btn.clipsToBounds = YES;
            //label 可以简化吗？
            TPLabel * label = [TPLabel labelWithText:title font:FONTSIZE_TITLE textColor:COLOUR_WHITE textAlignment:NSTextAlignmentCenter bgColor:colors[[titles indexOfObject:title]] numberOfLines:0 lineBreakMode:NSLineBreakByClipping];
            [btn addSubview:label];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.mas_equalTo(label.superview);
                make.top.bottom.mas_equalTo(label.superview);
                make.width.mas_equalTo(width);
            }];
            btn.tag = index ++;
//            [btn addTarget:self action:@selector(tapBtn:) forControlEvents:UIControlEventTouchUpInside];
            [btn setBackgroundColor:colors[[titles indexOfObject:title]]];
            UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapBtn:)];
            [btn addGestureRecognizer:tap];
            
//            [btn setTitle:title forState:UIControlStateNormal];
//            btn.titleLabel.numberOfLines = 0;
//            btn.titleLabel.textAlignment = NSTextAlignmentCenter;
//            btn.titleLabel.contentMode = UIViewContentModeCenter;
            [self addSubview:btn];
            
            
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.mas_equalTo(self);
                
                
                if (lastBtn) {
                    make.width.mas_equalTo(lastBtn);
                    make.left.mas_equalTo(lastBtn.mas_right);
                }else{
//                    make.width.mas_equalTo(width);
                    make.left.mas_equalTo(self);
                }
            }];
            lastBtn = btn;
        }
        
        
        [lastBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self);
        }];

    }
    return self;
}
- (void)tapBtn:(UITapGestureRecognizer *)sender{
    [self.delegate tapCellItilityBtnsBtn:sender.view];
}
@end


#pragma mark ------TPBaseTableViewCell------
@interface TPBaseTableViewCell()<UIScrollViewDelegate,TPCellUtilityBtnsDelegate>

PRO_S UITableView * parentTableView;
PRO_S UIScrollView * bgScrollView;
//PRO_S UIView * bgScrollViewContainer;
PRO_S UIView * centerView;

//PRO_S UIScrollView * bgScrollView;
//PRO_S UIView * bgContainer;
//PRO_S UIView * centerView;
////PRO_S TPCellUtilityBtns * leftBtns , * rightBtns;
//PRO_S UIView * rightUtilityBtnsContainer,* leftUtilityBtnsContainer;
//PRO_S UIView * centerViewRightSpace ,* centerViewLeftSpace;

@end

@implementation TPBaseTableViewCell




- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}
-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    UIView * view = [super hitTest:point withEvent:event];
    DDLogDebug(@"响应者：%@",view.debugDescription);
    return view;
}

#pragma  mark - ~~~life circle
- (void)prepareForReuse{
    [super prepareForReuse];
    [self updateCellState:TPBaseTableViewCellState_Normal willSetOffset:YES animated:NO];
}

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier rightBtns:(TPCellUtilityBtns *)rBtns leftBtns:(TPCellUtilityBtns *)lBtns{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        //    self.contentView.frame = self.bounds;
//           self.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
        //addSubview
        //bgscrollview
        
        _bgScrollView = [UIScrollView new];
//        _bgScrollView.translatesAutoresizingMaskIntoConstraints = NO;
        self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
        _bgScrollView.scrollEnabled = YES;
        _bgScrollView.showsVerticalScrollIndicator = NO;
        _bgScrollView.showsHorizontalScrollIndicator = NO;
        _bgScrollView.alwaysBounceVertical = NO;
        _bgScrollView.alwaysBounceHorizontal = NO;
        _bgScrollView.delegate = self;
        [_bgScrollView setDecelerationRate:0]; //0 依然有惯性
        
        
        
        //centerView
        _centerView = [UIView new];
        //    _centerView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
        
        [_bgScrollView addSubview:_centerView];
        
        for (UIView * subView in self.subviews) {
            [_centerView addSubview:subView];
        }
        //    [_bgScrollViewContainer addSubview:_centerView ];
        [_bgScrollView addSubview:_centerView];
        
        [self insertSubview:_bgScrollView atIndex:0];
        
        
        
        
        
        
        if (lBtns) {
//            _leftUtilityBtnsContainer = [UIView new];
//            [_leftUtilityBtnsContainer addSubview:lBtns];
//            _leftUtilityBtnsContainer.clipsToBounds = YES;
            _leftUtilityBtnsContainer = lBtns;
            lBtns.delegate = self;
            
        }else{
            _leftUtilityBtnsContainer = (TPCellUtilityBtns *)[[UIView alloc]init];
            
        }
        
        [_bgScrollView insertSubview:_leftUtilityBtnsContainer belowSubview:_centerView];
        
        
        
        if (rBtns) {
            _rightUtilityBtnsContainer = rBtns;
            
            rBtns.delegate = self;
        }else{
            _rightUtilityBtnsContainer = (TPCellUtilityBtns *)[[UIView alloc]init];
        }
        [_bgScrollView insertSubview:_rightUtilityBtnsContainer belowSubview:_centerView];
        
        
        
        
        //constraints
        
        [_centerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self.contentView).priorityHigh();
            // 高度将由内部撑起来
        }];
        
        [_leftUtilityBtnsContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self);
            make.top.bottom.mas_equalTo(self);
            //        make.width.mas_equalTo(0);
            
        }];
        
        [_rightUtilityBtnsContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self);
            make.top.bottom.mas_equalTo(self);
            //        make.width.mas_equalTo(0);
            
        }];
        //        [_rightUtilityBtnsContainer setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
        
        
        
        [_bgScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            //            make.left.right.mas_equalTo(self);
            //            make.top.bottom.mas_equalTo(self);
            make.edges.mas_equalTo(self);
        }];
        
        
        //    原理
        //-------------|----------------|------------
        //Inset_left   |contenSize_width| inset_right
        //offset       |0
        //设置offset 偏移量

        
    }
    
    
    
    return self;
}

//-(void)willMoveToSuperview:(UIView *)newSuperview{
//    super willMoveToSuperview:newSuperview
//}

- (void)didMoveToSuperview{
    [super didMoveToSuperview];
    self.parentTableView = (UITableView *)self.superview.superview;
    [self.parentTableView setDirectionalLockEnabled:YES];
    [self.parentTableView.panGestureRecognizer addObserver:self forKeyPath:@"state" options:0 context:nil];//用于检测 tableview pan的手势，如果未操作self cell ，则还原初始状态
}

//第一次出现 和 转屏 多次触发
- (void)layoutSubviews{
    [super layoutSubviews];
//修正contenView 宽度
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(SCREAN_WIDTH).priorityHigh();
    }];
//修正_bgScrollView.contentInset
    _bgScrollView.contentInset = UIEdgeInsetsMake(0, (_leftUtilityBtnsContainer.width_max * _leftUtilityBtnsContainer.numberOfBtn), 0, _rightUtilityBtnsContainer.width_max * _rightUtilityBtnsContainer.numberOfBtn );
    [_bgScrollView setContentSize:CGSizeMake(SCREAN_WIDTH, CGRectGetHeight(self.contentView.frame))];
    
//    修正转屏offset不为0
    if(self.state ==TPBaseTableViewCellState_Normal){
        [self updateCellState:TPBaseTableViewCellState_Normal willSetOffset:YES animated:NO];
    }else{
        [_parentTableView scrollRectToVisible:self.frame animated:NO];
    }
    
    
    
}
#pragma mark - ~~~private method





- (CGPoint)targetOffsetForCellState:(TPBaseTableViewCellState)state{
    CGPoint t =CGPointZero;
    switch (state) {
        case TPBaseTableViewCellState_Right:
            t.x = -_leftUtilityBtnsContainer.width_max * _leftUtilityBtnsContainer.numberOfBtn;//0;
            break;
        case TPBaseTableViewCellState_Left:
            t.x = _rightUtilityBtnsContainer.width_max * _rightUtilityBtnsContainer.numberOfBtn;//_rightUtilityBtnsContainer.subviews[0].bounds.size.width + _leftUtilityBtnsContainer.subviews[0].bounds.size.width;
            break;
            
        case  TPBaseTableViewCellState_Normal:
            t.x =  0;//_leftUtilityBtnsContainer.subviews[0].bounds.size.width;
            break;
    }
    return t;
}
- (void)updateCellState:(TPBaseTableViewCellState )state willSetOffset:(BOOL)willSetOffset animated:(BOOL)animated{
    CGPoint targetPoint = CGPointZero;
    
    switch (state) {
        case TPBaseTableViewCellState_Right:
        {
            targetPoint =[self targetOffsetForCellState:TPBaseTableViewCellState_Right];
            
            _state = TPBaseTableViewCellState_Right;

            
        }
            break;
        case TPBaseTableViewCellState_Left:
        {
            targetPoint = [self targetOffsetForCellState:TPBaseTableViewCellState_Left];
            
            _state = TPBaseTableViewCellState_Left;
            
        }
            break;
        case TPBaseTableViewCellState_Normal:
        {
            targetPoint = [self targetOffsetForCellState:TPBaseTableViewCellState_Normal];
            
            _state = TPBaseTableViewCellState_Normal;
            
        }
            break;
            
        default:
            break;
    }
    if (willSetOffset) {
        [_bgScrollView setContentOffset:targetPoint animated:animated];
        [self layoutIfNeeded];
    }
    
    
}
#pragma mark - ~~~public method

- (void)updateCellState:(TPBaseTableViewCellState )state OffSetAnimated:(BOOL)animated{
    [self updateCellState:state willSetOffset:YES animated:animated];
}


#pragma  mark - ~~~UtilityBtns delegate
- (void)tapCellItilityBtnsBtn:(UIButton *)btn{
    if (self.delegate && [self.delegate respondsToSelector:@selector(cell:indexPath:tapUtilityBtnsSide:btnIndex:)]) {
        [self.delegate cell:self indexPath:[self.parentTableView indexPathForCell:self] tapUtilityBtnsSide:[btn.superview isEqual:_rightUtilityBtnsContainer]?UtilityBtnsSide_right:UtilityBtnsSide_Left btnIndex:btn.tag];
    }

    
}

#pragma mark - ~~~scrollView ddelegate
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    DDLogDebug(@"velocity:%f,%f ,offset : %f,%f",velocity.x,velocity.y,targetContentOffset->x , targetContentOffset->y);
    

    if (fabs(velocity.x) > 0.6f ) {
        bool isSlideToLeft = velocity.x > 0;//判断滑动方向
//        if(velocity.x > 0){//向左划
            if ( targetContentOffset->x < [self targetOffsetForCellState:TPBaseTableViewCellState_Normal].x) {
                [self updateCellState:isSlideToLeft?TPBaseTableViewCellState_Normal:TPBaseTableViewCellState_Right willSetOffset:NO animated:YES];
            }else if(targetContentOffset->x > [self targetOffsetForCellState:TPBaseTableViewCellState_Normal].x){
                [self updateCellState:isSlideToLeft?TPBaseTableViewCellState_Left:TPBaseTableViewCellState_Normal willSetOffset:NO animated:YES];
            }else{
                //不可跨越2个状态
                if (_state == TPBaseTableViewCellState_Normal) {
                    [self updateCellState:isSlideToLeft?TPBaseTableViewCellState_Left:TPBaseTableViewCellState_Right willSetOffset:NO animated:YES];
                }else{
                    [self updateCellState:TPBaseTableViewCellState_Normal willSetOffset:NO animated:YES];
                }
                
            }

    }else{
        if (targetContentOffset->x < [self targetOffsetForCellState:TPBaseTableViewCellState_Right].x/2 ){
            [self updateCellState:TPBaseTableViewCellState_Right willSetOffset:NO animated:YES];
        }else if (targetContentOffset->x > TPBaseTableViewCellState_Left){
            [self updateCellState:TPBaseTableViewCellState_Left willSetOffset:NO animated:YES];
        }
        else{
            [self updateCellState:TPBaseTableViewCellState_Normal willSetOffset:NO animated:YES];
        }
    }
    
    *targetContentOffset = [self targetOffsetForCellState:_state];
    for ( TPBaseTableViewCell * cell in _parentTableView.visibleCells ) {
        if(cell.state != TPBaseTableViewCellState_Normal && ![self isEqual:cell]){
            [cell updateCellState:TPBaseTableViewCellState_Normal willSetOffset:YES animated:YES];
        }
        
    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    DDLogDebug(@"offset:%f:%f", _bgScrollView.contentOffset.x,_bgScrollView.contentOffset.y);
//    DDLogDebug(@"%f",_rightUtilityBtnsContainer.bounds.size.width);
    if(scrollView.contentOffset.x > 0){
        [_rightUtilityBtnsContainer mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(scrollView.contentOffset.x);
        }];
        [_leftUtilityBtnsContainer mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(0);
        }];
        
    }else if(scrollView.contentOffset.x < 0){
        [_leftUtilityBtnsContainer mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(-scrollView.contentOffset.x);
        }];
        [_rightUtilityBtnsContainer mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(0);
        }];
    }else{
        
    
        
    }
    

    
}





#pragma mark ~~~ KVO
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
//    DDLogWarn(@"panGestureRecognizer %@",_parentTableView.panGestureRecognizer);
    if ([object isEqual:_parentTableView.panGestureRecognizer] && [keyPath isEqualToString:@"state"]) {
//        DDLogDebug(@"panGestureRecognizer %@",_parentTableView.panGestureRecognizer);
        if (_parentTableView.panGestureRecognizer.state == UIGestureRecognizerStateBegan) {
            CGPoint location = [_parentTableView.panGestureRecognizer locationInView:_parentTableView];
            if(!CGRectContainsPoint(self.frame, location) && _state != TPBaseTableViewCellState_Normal){
                [self updateCellState:TPBaseTableViewCellState_Normal willSetOffset:YES animated:YES];
            }
        }
    }
}
-(void)dealloc{
    [_parentTableView removeObserver:self forKeyPath:@"state"];
}
@end
